package weaver.workflow.cms.xiao.schedule;

import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.weaver.general.TimeUtil;
import com.weaver.general.Util;
import weaver.conn.RecordSet;
import weaver.formmode.data.ModeDataIdUpdate;
import weaver.formmode.setup.ModeRightInfo;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.workflow.cms.xiao.entity.VendorItem;
import weaver.workflow.cms.xiao.entity.VendorResult;
import weaver.workflow.cms.xiao.utils.RequestBaseInfo;
import weaver.workflow.cms.xiao.utils.RequestUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author XiaoBokang
 * @create 2021/10/9 12:10
 */

public class VendorSyncSchedule extends BaseCronJob {


    private String formModeId;//建模id
    private String vendorSyncUrl;//请求地址
    private String vendorSyncKey;//key
    private String pageSize;
    private String ToKen;

    private Integer totalPage = 1;


    private final ToolUtil toolUtil = new ToolUtil();//工具类用于打印日志及其他操作
    public static final String CLASS_NAME = "VendorSyncSchedule";
    private final ModeDataIdUpdate mdu = ModeDataIdUpdate.getInstance();
    private final ModeRightInfo mri = new ModeRightInfo();

    private final Map<String, String>  subCompanyMap = new HashMap<>();//分部信息，分部全称对应id
    private final Map<String,String> subCompanyDescMap = new HashMap<>();//分部信息，分部全称对应简称
    private final Map<String,String> oneVendorMap = new HashMap<>();//各个分部的一次性供应商编码
//    private final Map<String,String> vendorList = new HashMap<>();//数据库中已存在的供应商列表
    private final List<Integer> maids = new ArrayList<>();//供应商主键集合

    {
        oneVendorMap.put("PCN","700000410");
        oneVendorMap.put("PHK","702000290");
        oneVendorMap.put("space4.0","700000410");
        oneVendorMap.put("PSCN","400300000");
        oneVendorMap.put("PFLCN","400300000");
        oneVendorMap.put("PDC","700000410");
        oneVendorMap.put("PMAP","700000410");
    }

    @Override
    public void execute() {
        toolUtil.writeDebuggerLog(CLASS_NAME,"--------------------"+CLASS_NAME+" begin-------------------");
        toolUtil.writeDebuggerLog(CLASS_NAME,"参数formModeId："+formModeId+" vendorSyncUrl:"+vendorSyncUrl+" vendorSyncKey:"+vendorSyncKey+" pageSize:"+pageSize);

        int pageSizeParam = Util.getIntValue(pageSize,500);
        Map<String,String> headers = new HashMap<>();
        Map<String,Object> params = new HashMap<>();
        params.put("ToKen",ToKen);
        headers.put("apiKey",vendorSyncKey);
        int page = 1;
        boolean flag = true;
        //做do-while循环发送请求，同步供应商信息
        try {
            do {
                params.put("pageSize", pageSizeParam);
                params.put("page", page);
                toolUtil.writeDebuggerLog(String.format("请求同步：url->{%s},参数ToKen->{%s},参数apiKey->{%s},参数pageSize->{%s},参数page->{%s}"
                        ,vendorSyncUrl,ToKen,vendorSyncKey,pageSizeParam,page));
                VendorResult res = RequestUtil.apiRequest(RequestBaseInfo.create(
                        "GET",
                        vendorSyncUrl,
                        headers,
                        params
                ), VendorResult.class);
                if (res != null && res.getCode()) {
                    //初始化只有在请求成功并且只做一次
                    if (flag) {
                        totalPage = res.getContent().getTotalPage();
                        //将数据库已经存在的供应商列表查询出来，将分部信息初始化
                        flag = false;
                    }
                    this.getVendorListBySql();
                    toolUtil.writeDebuggerLog(CLASS_NAME, "request success：");
                    toolUtil.writeDebugLog("get totalPages:"+res.getContent().getTotalPage());
                    //进行具体插入操作
                    this.insetVendor(res.getContent().getItems());
                }
            } while (page++ < totalPage);
        }catch (Exception e){
            toolUtil.writeDebuggerLog(CLASS_NAME,"发生异常");
            toolUtil.writeDebugLog(e);
        }
        //在所有信息更新之后，另外开一个线程来进行数据权限重构
        new Thread(new VendorSyncTheard(1,Util.getIntValue(formModeId,-1),maids,mri)).start();
        toolUtil.writeDebuggerLog(CLASS_NAME,"--------------------"+CLASS_NAME+" over-------------------");
    }

    /**
     * 向建模表插入供应商数据
     * @param itemList 供应商集合
     */
    private void insetVendor(List<VendorItem> itemList){
        RecordSet rs = new RecordSet();
        toolUtil.writeDebuggerLog("向建模表添加数据："+JSON.toJSONString(itemList.size()));
        RecordSet update_recordRes = new RecordSet();
        //进行批量更新的list
        List<List> bachList = new ArrayList<>();
        //进行批量修改的sql语句
        String updateSql = "update uf_gyszsjb set vendorCode = ?,vendorNameCn = ?,vendorNameEn = ?,vatRegNo = ?" +
                ",addressEn = ?,nationalType = ?,isRelatedParty = ?,businessPartnerCheckNumber = ?,organization = ?" +
                ",szfb=?,sfdlgys= ?,ywhbsc = ?,vendorType = ?,fadadaechapter = ? where id = ?";
        for (VendorItem vendorItem : itemList) {
            //进行数据更新时的参数集合
            List<Object> vendorParamList = new ArrayList<>();
            String query = "select id from uf_gyszsjb where ";
            StringBuilder stringBuilder = new StringBuilder(query);
            List<String> args = new ArrayList<>();
//             = ? and vendorNameCn = ? and vendorNameEn = ? and vatRegNo = ?
            if(vendorItem.getVendorCode() == null){
                stringBuilder.append("vendorCode is null ");
            }else{
                stringBuilder.append("vendorCode = ? ");
                args.add(vendorItem.getVendorCode());
            }
            /*if(vendorItem.getVendorNameCn() == null){
                stringBuilder.append(" and vendorNameCn is null ");
            }else{
                stringBuilder.append(" and vendorNameCn = ? ");
                args.add(vendorItem.getVendorNameCn());
            }
            if(vendorItem.getVendorNameEn() == null){
                stringBuilder.append(" and vendorNameEn is null ");
            }else{
                stringBuilder.append(" and vendorNameEn = ? ");
                args.add(vendorItem.getVendorNameEn());
            }
            if(vendorItem.getVatRegNo() == null){
                stringBuilder.append(" and vatRegNo is null ");
            }else{
                stringBuilder.append(" and vatRegNo = ? ");
                args.add(vendorItem.getVatRegNo());
            }*/
            if(vendorItem.getOrganization() == null){
                stringBuilder.append(" and organization is null ");
            }else{
                stringBuilder.append(" and organization = ? ");
                args.add(vendorItem.getOrganization());
            }
            rs.executeQuery(stringBuilder.toString(),args);
            int mainId = -1;
            if(rs.next()){
                mainId = rs.getInt("id");
//                toolUtil.writeDebuggerLog("查询到数据id：" + mainId);
            }
//            int mainId = Util.getIntValue(vendorList.get(vendorItem.getVendorCode()+","+vendorItem.getVendorNameCn()+","+vendorItem.getVendorNameEn()+","+vendorItem.getVatRegNo()),-1);
            //将分部全程转换成简称
            String companyName = Util.null2String(subCompanyDescMap.get(vendorItem.getOrganization()));
            //是否大陆供应商
            int sfdlgys = 1;
            if("China".equals(vendorItem.getNationalType())){
                sfdlgys = 0;
            }
            //是否为一次性供应商
            int vendorType = 1;
            if(oneVendorMap.get(companyName) != null && oneVendorMap.get(companyName).equals(vendorItem.getVendorCode())){
                vendorType = 0;
            }
            //所属分部
            int szfb = Util.getIntValue(subCompanyMap.get(vendorItem.getOrganization()),-1);
            //是否业务伙伴审查
            int ywhbsc = 1;
            if(vendorItem.getBusinessPartnerCheckNumber() != null && !"".equals(vendorItem.getBusinessPartnerCheckNumber())){
                ywhbsc = 0;
            }
            //判断数据库是否存在此条记录，若存在则进行更新操作
            if(mainId == -1){
                mainId =  mdu.getModeDataNewId("uf_gyszsjb", Util.getIntValue(formModeId,-1), 1, 0, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString());
            }
//            String updateSql = "update uf_gyszsjb set vendorCode = ?,vendorNameCn = ?,vendorNameEn = ?,vatRegNo = ?" +
//                    ",addressEn = ?,nationalType = ?,isRelatedParty = ?,businessPartnerCheckNumber = ?,organization = ?" +
//                    ",szfb=?,sfdlgys= ?,ywhbsc = ?,vendorType = ? where id = ?";
//            long l1 = System.currentTimeMillis();
//            update_recordRes.executeUpdate(updateSql,
//                    vendorItem.getVendorCode(),
//                    vendorItem.getVendorNameCn(),
//                    vendorItem.getVendorNameEn(),
//                    vendorItem.getVatRegNo(),
//                    vendorItem.getAddressEn(),
//                    vendorItem.getNationalType(),
//                    vendorItem.getIsRelatedParty(),
//                    vendorItem.getBusinessPartnerCheckNumber(),
//                    vendorItem.getOrganization(),
//                    szfb,
//                    sfdlgys,
//                    ywhbsc,
//                    vendorType,
//                    mainId
//            );
//            long l2 = System.currentTimeMillis();
//            System.out.println("执行数据更新用时："+(l2-l1));
//            maids.add(mainId);
            vendorParamList.add(vendorItem.getVendorCode());
            vendorParamList.add(vendorItem.getVendorNameCn());
            vendorParamList.add(vendorItem.getVendorNameEn());
            vendorParamList.add(vendorItem.getVatRegNo());
            vendorParamList.add(vendorItem.getAddressEn());
            vendorParamList.add(vendorItem.getNationalType());
            vendorParamList.add(vendorItem.getIsRelatedParty());
            vendorParamList.add(vendorItem.getBusinessPartnerCheckNumber());
            vendorParamList.add(vendorItem.getOrganization());
            vendorParamList.add(szfb);
            vendorParamList.add(sfdlgys);
            vendorParamList.add(ywhbsc);
            vendorParamList.add(vendorType);
            vendorParamList.add(vendorItem.getFadadaEchapter());
            vendorParamList.add(mainId);

            bachList.add(vendorParamList);
            maids.add(mainId);
        }
        //进行批量操作
        toolUtil.writeDebuggerLog("执行批量操作："+updateSql);
        update_recordRes.executeBatchSql(updateSql,bachList);
    }

    /**
     * 查询出数据库已经存在的供应商列表
     * 查询出分部信息
     */
    private void getVendorListBySql(){
        String query_vendor_list = "select id,vendorCode,vendorNameCn,vendorNameEn,vatRegNo from uf_gyszsjb";
        String query_subCompany_list = "select id,subcompanyname,subcompanydesc from HrmSubCompany";
        RecordSet recordSet = new RecordSet();
        RecordSet subCompany_recordset = new RecordSet();
        toolUtil.writeDebuggerLog("执行查询，供应商列表与分部信息：");
        recordSet.executeQuery(query_vendor_list);
        subCompany_recordset.executeQuery(query_subCompany_list);
//        while (recordSet.next()){
//            String vendorCode = Util.null2String(recordSet.getString("vendorCode"));
//            String vendorNameCn = Util.null2String(recordSet.getString("vendorNameCn"));
//            String vendorNameEn = Util.null2String(recordSet.getString("vendorNameEn"));
//            String vatRegNo = Util.null2String(recordSet.getString("vatRegNo"));
//            String mainId = Util.null2String(String.valueOf(recordSet.getString("id")));
//            vendorList.put(vendorCode+","+vendorNameCn+","+vendorNameEn+","+vatRegNo,mainId);
//        }
        while(subCompany_recordset.next()){
            String subCompanyName = Util.null2String(subCompany_recordset.getString("subcompanyname"));
            String subCompanyDesc = Util.null2String(subCompany_recordset.getString("subcompanydesc"));
            String mainId = Util.null2String(String.valueOf(subCompany_recordset.getString("id")));
            subCompanyDescMap.put(subCompanyDesc,subCompanyName);
            subCompanyMap.put(subCompanyDesc,mainId);
        }
//        toolUtil.writeDebuggerLog("查询成功，数据库原有供应商长度为==>"+vendorList.size());
        toolUtil.writeDebuggerLog("查询成功：分部简称全程对应信息:"+JSON.toJSONString(subCompanyDescMap)+" \n 分部信息id对应："+JSON.toJSONString(subCompanyMap));
    }

    public String getFormModeId() {
        return formModeId;
    }

    public void setFormModeId(String formModeId) {
        this.formModeId = formModeId;
    }

    public String getVendorSyncUrl() {
        return vendorSyncUrl;
    }

    public void setVendorSyncUrl(String vendorSyncUrl) {
        this.vendorSyncUrl = vendorSyncUrl;
    }

    public String getVendorSyncKey() {
        return vendorSyncKey;
    }

    public void setVendorSyncKey(String vendorSyncKey) {
        this.vendorSyncKey = vendorSyncKey;
    }

    public String getPageSize() {
        return pageSize;
    }

    public void setPageSize(String pageSize) {
        this.pageSize = pageSize;
    }

    public String getToKen() {
        return ToKen;
    }

    public void setToKen(String toKen) {
        ToKen = toKen;
    }
}
